*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	Bins offers and pscores by school-VAM.
*
*	OPTIONS
*		n - number of bins
*		ptype - type of propensity scores: "form", "freq", "iform", "ifreq"
*		vam - a var containing school-specific-VAMs (e.g. produced by olsvam.ado)
*	----------------------------------------------------------------------------

	program define vambin, rclass
	cap program drop vambin
	syntax [if] [in], n(integer) ptype(name) vam(name) [split(varname)]

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	marksample touse

	cap drop bin*
	if _rc == 0 di "Replacing existing bin vars"

	//pscore type
	local type = subinstr("`ptype'","i","",1)

	if "`split'"==""{
		tempvar schtag bin

		//bin yearly VAMs
		qui egen `schtag' = tag(sch) if lottery_`ptype'_sch & `touse'
		qui xtile `bin' = `vam' if !mi(`vam') & `schtag' & `touse', nquantiles(`n')

		forval i=1/`n'{
			qui levelsof sch if `bin' == `i', local(bin`i'_schs)
			//bin pscores
			qui gen binpscore_`type'_`i' = 0
			foreach sch in `bin`i'_schs'{
				qui replace binpscore_`type'_`i' = binpscore_`type'_`i' + pscore_`type'_`sch'
			}
			qui replace binpscore_`type'_`i' = min(binpscore_`type'_`i',1)
			//bin offers
			qui gen binoffer_`i' = 0
			foreach sch in `bin`i'_schs'{
				qui replace binoffer_`i' = binoffer_`i' + offer_`sch'
			}
			//some kids receive multiple offers in BOS
			qui replace binoffer_`i' = min(binoffer_`i',1)
		}
	}
	else{
		qui levelsof `split', local(levels)
		foreach l in `levels'{
			tempvar schtag bin

			//bin yearly VAMs
			qui egen `schtag' = tag(sch) if lottery_`ptype'_sch & `touse'
			qui xtile `bin' = `vam' if !mi(`vam') & `schtag' & `split'==`l' & `touse', nquantiles(`n')

			forval i=1/`n'{
				qui levelsof sch if `bin' == `i', local(bin`i'_schs)
				//bin pscores
				qui gen binpscore_`type'_s`l'_`i' = 0
				foreach sch in `bin`i'_schs'{
					qui replace binpscore_`type'_s`l'_`i' = binpscore_`type'_s`l'_`i' + pscore_`type'_`sch'
				}
				qui replace binpscore_`type'_s`l'_`i' = min(binpscore_`type'_s`l'_`i',1)
				//bin offers
				qui gen binoffer_s`l'_`i' = 0
				foreach sch in `bin`i'_schs'{
					qui replace binoffer_s`l'_`i' = binoffer_s`l'_`i' + offer_`sch'
				}
				//some kids receive multiple offers in BOS
				qui replace binoffer_s`l'_`i' = min(binoffer_s`l'_`i',1)
			}
		}
	}
	//dummy out scores
	if strpos("`ptype'","i")>0{
		foreach pscore of varlist binpscore_`type'_*{
			local iscore = subinstr("`pscore'","`type'","i`type'",1)
			qui egen `iscore' = group(`pscore')
		}
	}
	else{
		foreach pscore of varlist binpscore_`type'_*{
			qui gen `pscore'_0 = (`pscore' == 0)
		}
	}

	//define the lottery sample
	sharpsample if `touse', ptype(`ptype') bin goodcell

	end
